/******************************************************************************
 * This file is part of libemb.
 *
 * libemb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * libemb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libemb.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Project: Embedme
 * Author : FergusZeng
 * Email  : cblock@126.com
 * git	  : https://git.oschina.net/cblock/embedme
 * Copyright 2014 @ ShenZhen ,China
*******************************************************************************/
#include "Tracer.h"
#include "ProcUtil.h"
#include "StrUtil.h"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <iostream>

#define  EXECUTE_TIMEOUT    (5)     /* 默认超时时间为5秒 */

using namespace std;
namespace libemb{
/**
 *  \brief  执行命令并取得命令输出字符串.
 *  \param  cmd 命令字符串.
 *  \param  result 命令输出.
 *  \param  timeout 命令超时时间(seconds,默认为5秒).
 *  \return 命令执行成功返回STATUS_OK,命令执行失败返回STATUS_ERROR.
 *  \note   注意:必须确保cmd能够自动结束,否则该函数将一直等待,无法退出!
 */
int ProcUtil::execute(std::string cmd, std::string& result, int timeout)
{
	FILE* fp = popen(cmd.c_str(),"r");
	if (NULL==fp)
	{
		TRACE_ERR("ProcUtil::execute(%s), popen failed.\n",cmd.c_str());
		return STATUS_ERROR;
	}
    //TRACE_REL("command:[%s]\n",cmd.c_str());
    result="";
    if (timeout<=0) 
    {
        timeout = EXECUTE_TIMEOUT;
    }
    int tout = timeout;
    time_t startTime = ::time(NULL);
    while (1)
    {
        time_t endTime = ::time(NULL);
        if ((endTime-startTime)<0 || 
            (endTime-startTime)>=timeout) 
        {
            break;
        }
        if (tout <= 0)
        {
            break;
        }
        int fd = fileno(fp);
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(fd, &readfds);
        struct timeval tv;
        tv.tv_sec = 1;
        tv.tv_usec= 0;
        int ret = select(fd + 1, &readfds, NULL, NULL, &tv);
        if (ret<=0 || (!FD_ISSET(fd, &readfds)))
        {
            tout -= 1;
            continue;
        }
        else
        {
            char buf[256]={0};
            ret = fread(buf, 1, sizeof(buf), fp);
            if(ret<=0)
            {
                break;
            }
            result += std::string(buf,ret);
        }  
    }
	pclose(fp);
	return STATUS_OK;
}

/**
 *  \brief  执行命令并取得命令输出字符串.
 *  \param  cmd 命令字符串.
 *  \param  timeout 命令超时时间(seconds,默认为5秒).
 *  \return 成功返回命令输出,失败返回空字符串.
 *  \note   注意:必须确保cmd能够自动结束,否则该函数将一直等待,无法退出!
 */
std::string ProcUtil::execute(std::string cmd, int timeout)
{
    std::string result="";
	FILE* fp = popen(cmd.c_str(),"r");
	if (NULL==fp)
	{
		TRACE_ERR("ProcUtil::execute(%s), popen failed.\n",cmd.c_str());
		return result;
	}
    //TRACE_REL("command:[%s]\n",cmd.c_str());
    if (timeout<=0) 
    {
        timeout = EXECUTE_TIMEOUT;
    }
    int tout = timeout;
    time_t startTime = ::time(NULL);
    while(1)
    {
        time_t endTime = ::time(NULL);
        if ((endTime-startTime)<0 || 
            (endTime-startTime)>=timeout) 
        {
            break;
        }
        if (tout<=0) 
        {
            break;
        }
        int fd = fileno(fp);
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(fd, &readfds);
        struct timeval tv;
        tv.tv_sec = 1;
        tv.tv_usec= 0;
        int ret = select(fd + 1, &readfds, NULL, NULL, &tv);
        if (ret<=0 || (!FD_ISSET(fd, &readfds)))
        {
            tout -= 1;
            continue;
        }
        else
        {
            char buf[256]={0};
            ret = fread(buf, 1, sizeof(buf), fp);
            if(ret<=0)
            {
                break;
            }
            result += std::string(buf,ret);
        } 
    }
	pclose(fp);
	return result;
}

std::vector<int> ProcUtil::getPidsByName(const char* processName)
{
    std::vector<int> pidList;
    Directory dir;
    dir.enter("/proc");
    std::vector<std::string> fileNameList = dir.listAll();
    int num = fileNameList.size();
    for(int i=0; i<num; i++) 
    {
        if (!StrUtil::isIntString(fileNameList[i].c_str()))
        {
            continue;
        }
        File file;
        std::string statusFile = "/proc/"+fileNameList[i]+"/status";
        if(!file.open(statusFile.c_str(), IO_MODE_RD_ONLY))
        {
            TRACE_ERR("ProcUtil::getPidsByName,can't open file:%s.\n",statusFile.c_str());
            continue;
        }
        std::string firstLine;
        if(STATUS_ERROR==file.readLine(firstLine))
        {
            TRACE_ERR("ProcUtil::getPidsByName,read file error:%s.\n",statusFile.c_str());
            continue;
        }
        std::vector<std::string> result=StrUtil::splitString(firstLine,":");
        if (result.size()!=2) 
        {
            continue;
        }
        std::string pid = StrUtil::trimEndingBlank(result[1]);
        if (pid==processName) 
        {
            pidList.push_back(atoi(fileNameList[i].c_str()));
        }
    }
    return pidList;
}
ProcFifo::ProcFifo()
{
}

ProcFifo::~ProcFifo()
{
}

bool ProcFifo::open(const char* devName,int ioMode)
{
    if (devName==NULL)
    {
        TRACE_ERR_CLASS("fifo name is NULL.\n");
        return false;
    }
    if(!File::isExist(devName))
    {
        int ret=mkfifo(devName,S_IFIFO|0666);
        if (ret<0) 
        {
            TRACE_ERR_CLASS("mkfifo error:%s.\n", ERROR_STRING); 
            return false;
        }
    }
    return m_file.open(devName,ioMode);
}

bool ProcFifo::close()
{
    return m_file.close();
}

int ProcFifo::readData(char * buf, int len, int usTimeout)
{
    return m_file.readData(buf,len);
}
int ProcFifo::writeData(const char *buf, int len, int usTimeout)
{
    return m_file.writeData(buf,len);
}

}